import { Provide, Inject, Config } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { JwtService } from '@midwayjs/jwt';

@Provide()
export default class TokenUtil {
  @Inject()
  jwtService: JwtService;

  @Inject()
  ctx: Context;

  @Config('jwt')
  configJwt;

  /**
   * 生成token
   * @param user 用户对象
   */
  generateToken(user) {
    const tokenInfo = {
      userId: user.id,
    };
    return this.jwtService.sign(tokenInfo, this.configJwt.secret, {
      expiresIn: this.configJwt.expiresIn,
    });
  }

  /**
   * 解析token
   * @param authorization header authorization对象
   */
  async verifyToken() {
    const parts = this.ctx.get('authorization').trim().split(' ');
    const [, token] = parts;
    const result = await this.jwtService.verify(token, this.configJwt.secret, {
      complete: true,
    });
    return result;
  }
}
